package com.sky.loveshop.config;

import com.sky.loveshop.entity.exception.BizException;
import com.sky.loveshop.entity.exception.BizExceptionEnum;
import com.sky.loveshop.utils.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/11/10 17:21
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 检查该请求是否需要进行 token 校验
        if (matches(requestURI)) {
            String token = request.getHeader("Authorization");
            if (token == null || !isValidToken(token)) {
                throw new BizException(BizExceptionEnum.WX_UN_AUTHORIZED);
                //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置未授权状态
                //return false; // 终止请求
            }
        }
        return true; // 允许请求继续
    }

    // token 校验
    private boolean isValidToken(String token) {
        Boolean validToken = tokenManager.isValidToken(token);
        return validToken; // 示例条件
    }

    // 通配符匹配逻辑，定义需要拦截的路径
    private boolean matches(String requestURI) {
        // 这里你可以定义符合条件的路径规则
        return requestURI.startsWith("/weChatMini/auth/"); // 例如：所有以 /weChatMini/auth/ 开头的请求
    }

}
